package com.ifinc.common.generate;

import com.ifinc.common.utils.web.FreeMarkerUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.io.File;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: luotao
 * Date: 11/30/13
 * Time: 3:35 PM
 */
@Service
public class GenerateService {


    private JdbcTemplate jdbcTemplate;

    private DataSource dataSource;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
        this.dataSource = dataSource;
    }

    public void gen(String tableName,String savePath,String filename) throws Exception{
        String sql = "select * from " + tableName + " limit 0,1";
        Map map = (Map) jdbcTemplate.query(sql, new MyRowMapperResultSetExtractor
                ("test",null,tableName,this.dataSource,new ColumnMapper()));
        map.put("tablename",tableName);
        String result = FreeMarkerUtil.getInstance().getStrByTemplate(map,"/template/ibatis.ftl");
        System.out.println("result = " + result);
        FileUtils.writeByteArrayToFile(new File(savePath+filename),result.getBytes());

        String resultClass = FreeMarkerUtil.getInstance().getStrByTemplate(map, "/template/ConstTable.ftl");
        String javaFileName = (String) map.get("tableNameForJava")+".java";
        System.out.println("resultClass = " + resultClass);
        FileUtils.writeByteArrayToFile(new File(savePath + javaFileName), resultClass.getBytes());
    }
}
